<template>
  <fieldset>
    <legend>home</legend>
    <!-- 登入之后的结构 -->
    <div class="content" v-if="loginchoise">
        <h2><a href=""></a>{{user.nickname}}</h2>
        <img :src="user.headimgurl" width="50" alt="">
        <button @click="out">点击退出</button>
        <!-- <button @click="getlist">点击获取列表</button> -->
      <ul>
        <li v-for="item in list" :key="item._id">
          <b>{{item.name}}</b>
          <button v-judge:add="permissionBtns">增加</button>
          <button v-judge:edit="permissionBtns">编辑</button>
          <button v-judge:delete="permissionBtns">删除</button>
          <button v-judge:read="permissionBtns">查看</button>
        </li>
      </ul>
    </div>
    <!-- 登入结构 -->
    <div v-else>
      <h1>请登入</h1>
      用户名:
      <input type="text" v-model="username">
      <br />
      密码:
      <input type="password" v-model="password" @keydown.enter="login">
      <br />
      <button @click="login">点击登入</button>
    </div>
  </fieldset>
</template>
<script>
import Vue from "vue";
export default{
    
    data(){
        return{
            username:"",
            password:"",
            loginchoise:false,
            user:{},
            list:{},
            permissionBtns:""
        }
    },
    methods:{
        login(){
            let arr ={
                username:this.username,
                password:this.password
            }
            fetch("http://chst.vip/users/login",{
                method:'post',
                body:JSON.stringify(arr),
                headers:{
                    'content-type':'application/json'
                }
            })
            .then(body=>body.json())
            .then(res=>{
                console.log(res)
                if(res.state){
                    this.loginchoise=true
                    this.user=res.userInfo
                    sessionStorage.setItem('user-token',res.token)
                    this.permissionBtns=res.permission.buttons
                     fetch('http://chst.vip/students/getstulist?count=5',{
                        method:'get',
                        headers:{
                            'authorization': sessionStorage.getItem('user-token')
                        }
                    })
                    .then(body=>body.json())
                    .then(res=>{
                        console.log(res)
                        if(res.state){
                            this.list=res.data
                        }
                    })
                }
            })
        },
        out(){
            this.loginchoise=false
        },
        // getlist(){
           
        // },
    }
}
Vue.directive("judge",{
    inserted(el,binding){
        console.log(binding)
        let role=binding.arg
        let userrole=binding.value
        let choiseRole=userrole.includes(role)
        if(!choiseRole){
            el.disabled=true
        }
    }
    })
</script>
